package com.tsp_tux.demo.Service;

import com.tsp_tux.demo.Mapper.ArticleMapper;
import com.tsp_tux.demo.Mapper.FileMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;


/**
 * @author 周志伟
 */
@Service
public class FileServiceImp implements FileService{

    @Resource
    private FileMapper fileMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int upLoadFile(String fileName, String url, String type, String uid, Integer aid, Integer sid) {
        try {
                if(aid == -1)
                    aid = null;
                if(sid == -1)
                    sid = null;
                if(fileMapper.findFileByUrl(url) == 0)
                    fileMapper.upLoadFile(fileName, url, type,uid,aid,sid);
                return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteFileByRid(Integer rid) {
        try {
            String url = fileMapper.findUrlByRid(rid);
            if(url == null)
                return 2;
            String address = url.replace("http://47.107.40.143:8081/","/home/tsp_tux/dist/");
            File file = new File(address);
            file.delete();
            fileMapper.deleteResourceByRid(rid);
            return 0;
        }
        catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }


}


